<?php
/**
 * 发货单处理
 *
 * @category 
 * @package 
 * @author chenping<chenping@shopex.cn>
 * @version $Id: Z
 */
class erpapi_shop_request_delivery extends erpapi_shop_request_abstract
{
    protected $_delivery_errcode = array(
        'W90010'=>'已经出库',
        'W90011'=>'参数错误',
        'W90012'=>'已经出库',
        'W90013'=>'参数错误',
        'W90014'=>'参数错误',
    );

    /**
     * 发货确认
     *
     * @return void
     * @author
     * @param Array $sdf = array(
     *                  'delivery_id' => #发货单ID#
     *                  'delivery_bn' => #发货单编号#
     *                  'status'      => #发货单状态#
     *                  'logi_id' => #物流公司ID#
     *                  'logi_name' => #物流公司名称#
     *                  'logi_no' => #运单号#
     *                  'logi_type' => #物流公司类型#
     *                  'feature' => #唯一码#
     *                  'is_split' => #是否拆单#
     *                  'split_model' => #拆单模式#
     *                  'is_cod' => #货到付款#
     *                  'oid_list'=> #子单#
     *                  'itemNum' => #包裹数#
     *                  'delivery_time' => #发货时间#
     *                  'last_modified' => #最后更新时间#
     *                  'delivery_cost_actual' => #物流费#
     *                  'create_time' => #创建时间#
     *                  'is_protect' => #是否保价#
     *                  'delivery' => #配送方式#
     *                  'memo' => #备注#
     *                  'is_virtual' => #是否为虚拟化发货#
     *                  'delivery_items' => array(
     *                      'bn' => #货号#
     *                      'number' => #数量#
     *                      'name' => #名称#
     *                      'item_type' => #明细类型#
     *                      'shop_goods_id' => #前端商品#
     *                      'promotion_id' => #优惠ID#
     *                  ),
     *                  'consignee' => array(
     *                      'name' => #收货人姓名#
     *                      'area' => #收货地区#
     *                      'addr' => #收货人地址#
     *                      'zip'  => #收货人邮编#
     *                      'email' => #收货人邮箱#
     *                      'mobile' => #收货人手机#
     *                      'telephone' => #收货人电话#
     *                  ),
     *                  'memberinfo' => array(
     *                      'uname' => #会员名#
     *                  ),
     *                  'orderinfo' => array(
     *                         'order_id' => #订单ID#
     *                         'order_bn' => #订单编号#
     *                         'ship_status' => #发货状态#
     *                         'createway' => #订单生成方式#
     *                         'sync'  => #回写状态#
     *                         'sellermemberid' => #买家ID#
     *                         'is_cod' => #到付#
     *                         'self_delivery' => #自发货#
     *                         'order_objects' => array(
     *                              'bn' => #货号#
     *                              'oid' => #子单编号#
     *                              'shop_goods_id' => #平台商品ID#
     *                              'quantity' => #数量#
     *                              'name' => #商品名称#
     *                              'obj_type' => #类型#
     *                              'order_items' => array(
     *                                  'bn' => #货号#
     *                                  'shop_goods_id' => #平台商品ID#
     *                                  'sendnum' => #发货数量#
     *                                  'product_name' => #商品名称#
     *                                  'promotion_id' => #优惠ID#
     *                                  'item_type' => #类型#
     *                                  'nums' => #购买数量#
     *                               ),
     *                          ),
     *                  ),
     *              )
     **/
    public function confirm($sdf,$queue=false)
    {
        // 只处理已发货与部分发货状态
        if ($sdf['status'] != 'succ' && !in_array($sdf['orderinfo']['ship_status'], array('1','2'))) return $this->succ('发货单未发货');

        $args[0] = $sdf;
        $_in_mq = $this->__caller->caller_into_mq('delivery_confirm','shop',$this->__channelObj->channel['shop_id'],$args,$queue);
        if ($_in_mq) {
            return $this->succ('成功放入队列');
        }

        $this->format_confirm_sdf($sdf);
        
        // 发货记录
        $opInfo = kernel::single('ome_func')->getDesktopUser();
        $log_id = uniqid($_SERVER['HOSTNAME']);
        $log = array(
            'shopId'           => $this->__channelObj->channel['shop_id'],
            'ownerId'          => $opInfo['op_id'],
            'orderBn'          => $sdf['orderinfo']['order_bn'],
            'deliveryCode'     => $sdf['logi_no'],
            'deliveryCropCode' => $sdf['logi_type'],
            'deliveryCropName' => $sdf['logi_name'],
            'receiveTime'      => time(),
            'status'           => 'send',
            'updateTime'       => '0',
            'message'          => '',
            'log_id'           => $log_id,
        );

        $shipmentLogModel = app::get('ome')->model('shipment_log');
        $shipmentLogModel->insert($log);

        // 更新订单状态
        $orderModel = app::get('ome')->model('orders');
        $orderModel->update(array('sync'=>'run'),array('order_id'=>$sdf['orderinfo']['order_id']));

        // 整理参数格式
        $title = sprintf('发货状态回写[%s]-%s',$sdf['delivery_bn'],$this->__channelObj->channel['node_type']);

        $params = $this->get_confirm_params($sdf);
       
        $callback = array(
           'class' => get_class($this),
           'method' => 'confirm_callback',
           'params' => array(
                'shipment_log_id' => $log_id,
                'order_id'        => $sdf['orderinfo']['order_id'],
                'logi_no'         => $sdf['logi_no'],
                'obj_bn' => $sdf['orderinfo']['order_bn'],
                'company_code'=>$sdf['logi_type'],
                 'delivery_bn'   =>  $sdf['delivery_bn'],
            ),

        );

        $result = $this->__caller->call($this->get_delivery_apiname($sdf), $params, $callback, $title,10,$sdf['orderinfo']['order_bn']);
       
        if ($result['rsp'] == 'fail') {
            $shipmentLogModel->update(array('status'=>'fail','message'=>$result['err_msg'],'updateTime'=>time()),array('log_id'=>$log_id));
        }

        return $result;
    }

    /**
     * 发货请求参数（以淘宝做为标准）
     *
     * @return void
     * @author 
     **/
    protected function get_confirm_params($sdf)
    {
        $param = array(
            'tid'          => $sdf['orderinfo']['order_bn'], // 订单号
            'company_code' => $sdf['logi_type'], // 物流编号
            'company_name' => $sdf['logi_name'], // 物流公司
            'logistics_no' => $sdf['logi_no'], // 运单号
        );
        
        return $param;
    }

    /**
     * 数据处理
     *
     * @return void
     * @author 
     **/
    protected function format_confirm_sdf(&$sdf)
    {
        // 物流发货单去BOM头
        $pattrn           = chr(239).chr(187).chr(191);
        $sdf['logi_no']   = trim(str_replace($pattrn, '', $sdf['logi_no']));
        $sdf['logi_type'] = trim($sdf['logi_type']);
        $sdf['logi_name'] = strval($sdf['logi_name']);
        $sdf['logi_no']   = strval($sdf['logi_no']);
    }

    /**
     * 发货回调
     *
     * @return void
     * @author 
     **/
    public function confirm_callback($response, $callback_params)
    {
        $rsp             = $response['rsp'];
        $msg_id          = $response['msg_id'];
        $res             = trim($response['res']);
        $err_msg         = $response['err_msg'];
        $order_id        = $callback_params['order_id'];
        $shipment_log_id = $callback_params['shipment_log_id'];
        $logi_no         = $callback_params['logi_no'];


        $orderModel    = app::get('ome')->model('orders');
        $order = $orderModel->getList('sync,shop_type',array('order_id'=>$order_id),0,1);

        // 已经回写成功，不需要再改
        if ($order[0]['sync'] == 'succ') $rsp = 'succ';

        if (preg_match("/签收/", $err_msg)){
            $rsp = 'succ';
        }
        // 出现需要重新的，重置
        if ($order[0]['shop_type'] == 'taobao' && false !== strstr($err_msg,'error_response')) {
            $errmsg = @json_decode($err_msg,true);
            if (is_array($errmsg)){
                $err_msg = $errmsg['error_response']['sub_msg'];

                if ($errmsg['error_response']['sub_code'] == 'B150') $rsp = 'fail';
            }
        }
        $rsp=='success' ? 'succ' : $rsp;
        $status = 'succ'; $sync_fail_type = 'none'; $message = '';
        // ERP没有发起成功且请求失败
        if ($rsp != 'succ' ) {
            $status = 'fail';

            

            // 错误信息
            $message = $err_msg.'('.$msg_id.')';

            // 失败类型
            if ('已经出库' == $this->_delivery_errcode[$res]) {
                $status = 'succ';
                $message = '已经出库'.$res.'('.$msg_id.')';

                $sync_fail_type = 'shipped';
            }elseif (in_array($res,array('W90011','W90013','W90014'))) {
                $sync_fail_type = 'params';
            }
        }

        // 更新订单状态
        if ($order_id) {
            $updateOrderData = array(
                'sync'           => $status,
                'up_time'        => time(),
                'sync_fail_type' => $sync_fail_type,
            );

            $orderModel->update($updateOrderData,array('order_id'=>$order_id,'sync|noequal'=>'succ'));
        }

        $shipmentModel = app::get('ome')->model('shipment_log');

        // 更新发货日志状态
        if ($shipment_log_id) {
            $updateShipmentData = array(
                'status'     => $status,
                'updateTime' => time(),
                'message'    => $message,
            );

            $shipmentModel->update($updateShipmentData,array('log_id'=>$shipment_log_id));
        }

        return $this->callback($response, $callback_params);
    }

    /**
     * 家装服务商
     *
     * @return void
     * @author 
     **/
    public function jzpartner_query($sdf)
    {
        $title = sprintf('家装服务商查询[%s]',$sdf['orderinfo']['order_bn']);

        $params = array(
            'taobao_trade_id'=>$sdf['orderinfo']['order_bn'],
        );

        $result=$this->__caller->call(SHOP_WLB_ORDER_JZPARTNER_QUERY, $params, null, $title,10,$sdf['delivery_bn']);

        $data = array();

        if ($result['rsp'] == 'succ') {
            $result['data'] = @json_decode($result['data'],true);

            if ($result['data']['server_list']['partner_new'])
                foreach ($result['data']['server_list']['partner_new'] as $partner) {
                    $tp_code = explode(';',$partner['tp_code']);

                    // 返回第一个
                    if ($sdf['logi_type'] == current($tp_code)) {
                        $data = $partner; break;
                    }
                }
        }

        return $data;
    }

    /**
     * 获取发货接口(默认线下发货)
     *
     * @return void
     * @author 
     **/
    protected function get_delivery_apiname($sdf)
    {
        return SHOP_LOGISTICS_OFFLINE_SEND;
    }

    /**
     * 添加发货单
     *
     * @return void
     * @author 
     **/
    public function add($sdf){}

    /**
     * 更新发货单流水状态
     *
     * @return void
     * @author 
     **/
    public function process_update($sdf){}

    /**
     * 更新物流公司
     *
     * @return void
     * @author 
     **/
    public function logistics_update($sdf){}

}
